package com.hm.common.su;

import com.hm.common.su.exception.ErrorCode;
import com.hm.common.su.exception.ServiceException;
import com.hm.common.su.util.AES;
import com.hm.common.su.util.CommonUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shishun.wang
 * @version 1.0
 * @date 2019/4/3 14:33
 * @describe
 */
public class SessionFactory {
	
	public final static HttpServletResponse getResponse() {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		return response;
	}
	
	public final static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	public final static Object getCurrentUser(){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		Object obj = request.getSession().getAttribute(CommonDef.SessionDef.HTTP_REQUEST_SESSION_ID);
		if (obj == null){
			throw ServiceException.warning(ErrorCode.SESSION_TIME_OUT);
		}
		return obj;
	}
	
	public final static Long getCurrentUserId() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		Cookie[] cookies = request.getCookies();
		if (CommonUtil.isNotEmpty(cookies)) {
			for (Cookie cookie : cookies) {
				if (CommonDef.SessionDef.HTTP_REQUEST_SESSION_ID.equals(cookie.getName())) {
					String decrypt = AES.decrypt(cookie.getValue());
					return Long.parseLong(decrypt.split(":")[0]);
				}
			}
		}
		String authorization = request.getHeader("REQUEST_AUTHORIZATION_KEY");
		if (authorization == null) {
			throw ServiceException.warning(ErrorCode.NO_DATA_ACCESS);
		}
		return Long.parseLong(authorization.split(":")[0]);
	}
}
